import { marked } from 'marked';
import hljs from 'highlight.js';

// 配置 marked
marked.setOptions({
  highlight: function(code, lang) {
    const language = hljs.getLanguage(lang) ? lang : 'plaintext';
    return hljs.highlight(code, { language }).value;
  },
  breaks: true,
  gfm: true,
  langPrefix: 'hljs language-'
});

// 解析 frontmatter
const parseFrontmatter = (content) => {
  const frontmatterRegex = /^---\s*\n([\s\S]*?)\n---\s*\n([\s\S]*)$/;
  const match = content.match(frontmatterRegex);
  
  if (!match) {
    return { metadata: {}, content };
  }
  
  const [, frontmatterStr, markdownContent] = match;
  const metadata = {};
  
  // 解析 YAML 格式的 frontmatter
  frontmatterStr.split('\n').forEach(line => {
    const colonIndex = line.indexOf(':');
    if (colonIndex > 0) {
      const key = line.substring(0, colonIndex).trim();
      let value = line.substring(colonIndex + 1).trim();
      
      // 处理数组格式 [item1, item2, item3]
      if (value.startsWith('[') && value.endsWith(']')) {
        value = value.slice(1, -1).split(',').map(item => item.trim());
      }
      // 处理布尔值
      else if (value === 'true') {
        value = true;
      } else if (value === 'false') {
        value = false;
      }
      
      metadata[key] = value;
    }
  });
  
  return { metadata, content: markdownContent };
};

// 生成笔记 ID（基于文件名）
const generateNoteId = (filename) => {
  return filename.replace('.md', '').replace(/[^a-zA-Z0-9-]/g, '-');
};

// 笔记分类配置 - 支持二级目录结构
const noteCategories = [
  {
    key: 'frontend',
    name: '前端开发',
    description: '前端技术栈学习笔记，包括 React、Vue、JavaScript、CSS 等',
    subcategories: [
      {
        key: 'javascript-es6-features',
        name: 'JavaScript 核心'
      },
      {
        key: 'react-hooks-guide',
        name: 'React 技术'
      },
      {
        key: 'vue3-composition-api',
        name: 'Vue 技术'
      }
    ]
  },
  {
    key: 'backend',
    name: '后端开发',
    description: '后端技术学习笔记，包括 Node.js、Java、Python、数据库等',
    subcategories: [
      {
        key: 'nodejs-best-practices',
        name: 'Node.js 开发'
      },
      {
        key: 'database-design-principles',
        name: '数据库设计'
      }
    ]
  },
  {
    key: 'devops',
    name: '运维部署',
    description: 'DevOps 相关技术，包括 Docker、Kubernetes、CI/CD 等',
    subcategories: [
      {
        key: 'docker-containerization',
        name: 'Docker 容器化'
      },
      {
        key: 'kubernetes-deployment',
        name: 'Kubernetes 部署'
      }
    ]
  },
  {
    key: 'architecture',
    name: '系统架构',
    description: '系统设计和架构模式，微服务、分布式系统等',
    subcategories: [
      {
        key: 'microservices-patterns',
        name: '微服务架构'
      },
      {
        key: 'system-design-fundamentals',
        name: '系统设计基础'
      }
    ]
  },
  {
    key: 'tools',
    name: '开发工具',
    description: '开发工具和效率提升，包括编辑器、调试工具等',
    subcategories: [
      {
        key: 'vscode-productivity-tips',
        name: 'VS Code 技巧'
      },
      {
        key: 'git-workflow-guide',
        name: 'Git 工作流'
      }
    ]
  }
];

// 检查是否为子分类
const isSubcategory = (categoryKey) => {
  for (const category of noteCategories) {
    if (category.subcategories) {
      const found = category.subcategories.find(sub => sub.key === categoryKey);
      if (found) {
        return { isSubcategory: true, parentCategory: category.key };
      }
    }
  }
  return { isSubcategory: false, parentCategory: null };
};

// 自动扫描笔记文件系统
const getNoteFiles = () => {
  const noteFiles = {};
  
  // 扫描各个分类目录
  const categories = ['frontend', 'backend', 'devops', 'architecture', 'tools'];
  
  categories.forEach(category => {
    try {
      // 使用 webpack 的 require.context 自动扫描每个分类目录
      const context = require.context('../../notes', true, /\.md$/);
      const categoryFiles = {};
      
      context.keys().forEach(key => {
        // 匹配当前分类的文件，例如 ./frontend/react-hooks-guide.md
        const match = key.match(new RegExp(`^\\./${category}/(.+\\.md)$`));
        if (match) {
          const filename = match[1];
          categoryFiles[filename] = () => context(key);
        }
      });
      
      if (Object.keys(categoryFiles).length > 0) {
        noteFiles[category] = categoryFiles;
      }
    } catch (error) {
      console.warn(`扫描笔记分类 ${category} 失败:`, error);
    }
  });
  
  return noteFiles;
};

// 获取笔记分类
export const getNoteCategories = async () => {
  return noteCategories;
};

// 获取扁平化的分类列表（包含子分类）
export const getFlatCategories = async () => {
  const flatCategories = [];
  
  noteCategories.forEach(category => {
    // 添加主分类
    flatCategories.push({
      key: category.key,
      name: category.name,
      description: category.description,
      isParent: true,
      parentKey: null
    });
    
    // 添加子分类
    if (category.subcategories) {
      category.subcategories.forEach(sub => {
        flatCategories.push({
          key: sub.key,
          name: sub.name,
          description: sub.description,
          isParent: false,
          parentKey: category.key,
          parentName: category.name
        });
      });
    }
  });
  
  return flatCategories;
};

// 根据笔记ID获取其所属的分类信息
export const getCategoryByNoteId = async (noteId) => {
  const allNotes = await loadAllNotes();
  const note = allNotes.find(n => n.id === noteId);
  
  if (!note) return null;
  
  // 查找对应的分类信息
  for (const category of noteCategories) {
    if (category.subcategories) {
      const subcategory = category.subcategories.find(sub => sub.key === noteId);
      if (subcategory) {
        return {
          parentCategory: category,
          subcategory: subcategory
        };
      }
    }
  }
  
  return null;
};

// 加载子分类对应的笔记
export const loadNotesBySubcategory = async (subcategoryKey) => {
  const allNotes = await loadAllNotes();
  // 子分类对应的是具体的笔记文件，按 ID 匹配
  const matchedNotes = allNotes.filter(note => note.id === subcategoryKey);
  console.log('子分类筛选:', subcategoryKey, '匹配到的笔记:', matchedNotes);
  return matchedNotes;
};

// 加载指定分类的所有笔记
export const loadNotesByCategory = async (category) => {
  console.log('加载分类笔记:', category);
  
  // 检查是否为子分类
  const subcategoryInfo = isSubcategory(category);
  console.log('子分类检查结果:', subcategoryInfo);
  
  if (subcategoryInfo.isSubcategory) {
    // 如果是子分类，加载对应的笔记
    console.log('这是子分类，调用 loadNotesBySubcategory');
    return await loadNotesBySubcategory(category);
  }
  
  // 如果是主分类，按原逻辑加载
  console.log('这是主分类，按原逻辑加载');
  const notes = [];
  const noteFiles = getNoteFiles();
  const categoryFiles = noteFiles[category] || {};
  console.log('主分类文件:', categoryFiles);
  
  for (const [filename, importFn] of Object.entries(categoryFiles)) {
    try {
      const module = await importFn();
      const content = module.default || module;
      const { metadata, content: markdownContent } = parseFrontmatter(content);
      
      const note = {
        id: generateNoteId(filename),
        category,
        title: metadata.title || '无标题',
        excerpt: metadata.excerpt || '',
        content: markdownContent,
        date: metadata.date || new Date().toISOString().split('T')[0],
        readTime: metadata.readTime || '5 分钟',
        tags: metadata.tags || [],
        order: metadata.order || 999
      };
      
      notes.push(note);
    } catch (error) {
      console.error(`加载笔记 ${category}/${filename} 失败:`, error);
    }
  }
  
  // 按 order 排序，然后按日期排序
  return notes.sort((a, b) => {
    if (a.order !== b.order) {
      return a.order - b.order;
    }
    return new Date(b.date) - new Date(a.date);
  });
};

// 根据笔记ID加载笔记（支持二级分类）
export const loadNoteByIdFromAnyCategory = async (noteId) => {
  const allNotes = await loadAllNotes();
  return allNotes.find(note => note.id === noteId);
};

// 获取分类下的笔记统计
export const getCategoryNotesCount = async () => {
  const allNotes = await loadAllNotes();
  const counts = {};
  
  // 统计每个分类的笔记数量
  noteCategories.forEach(category => {
    counts[category.key] = 0;
    
    if (category.subcategories) {
      category.subcategories.forEach(sub => {
        const noteCount = allNotes.filter(note => note.id === sub.key).length;
        counts[category.key] += noteCount;
        counts[sub.key] = noteCount;
      });
    } else {
      counts[category.key] = allNotes.filter(note => note.category === category.key).length;
    }
  });
  
  return counts;
};

// 加载所有笔记
export const loadAllNotes = async () => {
  const allNotes = [];
  const noteFiles = getNoteFiles();
  
  // 只加载主分类的笔记，避免递归调用
  for (const category of Object.keys(noteFiles)) {
    const categoryFiles = noteFiles[category] || {};
    
    for (const [filename, importFn] of Object.entries(categoryFiles)) {
      try {
        const module = await importFn();
        const content = module.default || module;
        const { metadata, content: markdownContent } = parseFrontmatter(content);
        
        const note = {
          id: generateNoteId(filename),
          category,
          title: metadata.title || '无标题',
          excerpt: metadata.excerpt || '',
          content: markdownContent,
          date: metadata.date || new Date().toISOString().split('T')[0],
          readTime: metadata.readTime || '5 分钟',
          tags: metadata.tags || [],
          order: metadata.order || 999
        };
        
        allNotes.push(note);
      } catch (error) {
        console.error(`加载笔记 ${category}/${filename} 失败:`, error);
      }
    }
  }
  
  console.log('所有笔记:', allNotes);
  
  // 按日期排序（最新的在前）
  return allNotes.sort((a, b) => new Date(b.date) - new Date(a.date));
};

// 根据分类和 ID 加载单篇笔记
export const loadNoteById = async (category, id) => {
  const categoryNotes = await loadNotesByCategory(category);
  return categoryNotes.find(note => note.id === id);
};
